package com.tataben.db.table;

import com.tataben.db.annotation.Table;
import com.tataben.db.util.DLTableUtils;

import java.lang.reflect.Constructor;
import java.util.LinkedHashMap;

public final class DLTable<T> {

    private final String name;
    private final String onCreated;
    private DLColumn id;
    private Class<T> entityType;
    private Constructor<T> constructor;
    private volatile boolean checkedDatabase;

    private final LinkedHashMap<String, DLColumn> columnMap;

    public DLTable(Class<T> entityType) throws Throwable {
        this.entityType = entityType;
        this.constructor = entityType.getConstructor();
        this.constructor.setAccessible(true);
        Table table = entityType.getAnnotation(Table.class);
        this.name = table.name();
        this.onCreated = table.onCreated();
        this.columnMap = DLTableUtils.findColumnMap(entityType);
        for (DLColumn column : columnMap.values()) {
            if (column.isId()) {
                this.id = column;
                break;
            }
        }
    }

    public T createEntity() throws Throwable {
        return this.constructor.newInstance();
    }

    public String getName() {
        return name;
    }

    public Class<T> getEntityType() {
        return entityType;
    }

    public String getOnCreated() {
        return onCreated;
    }

    public DLColumn getId() {
        return id;
    }

    public LinkedHashMap<String, DLColumn> getColumnMap() {
        return columnMap;
    }

    public boolean isCheckedDatabase() {
        return checkedDatabase;
    }

    public void setCheckedDatabase(boolean checkedDatabase) {
        this.checkedDatabase = checkedDatabase;
    }

    public String toString() {
        return name;
    }
}
